<?php
class UserSaveSetupAction extends FrontendAction
{
	public function __construct()
	{
		parent::__construct();
		$this->responseType = 'json';
	}
	
	protected function afterConstruct()
	{
		$this->parseDtds('user','setup');
	}
	
	public function execute()
	{
		if(!$this->data['user'])
		{
			$data			= $this->getValidData();
			$username		= htmlspecialchars(trim($data['username']));
			$password		= strip_tags(trim($data['password']));

			$userService	= new BaseDbService('user');
			$tmp	= $userService->count(array('username'=>'eq:'.$username));
			if($tmp)
			{
				$this->data['error_messages']['username']	= array('lower'=>'该昵称已经被其他用户使用');
			}
			
			//验证通过，更新数据库
			if(empty($this->data['error_messages']))
			{
				$update		= array('username'=>$username, 'password'=>$password);
				$update['secques']	= Util::random(8);
				$update['password']	= Util::generatePassword($update['password'],$update['secques']);
				//新增用户
				$id	= $userService->add($update);
				if($id>0)
				{
					//注册成功，进行登陆
					$user		= $userService->get($id);
					if($user)
					{
						$expire		= time() + 1200;
						$authCode 	= $id . "\t" . $user['username']. "\t" .$user['password']. "\t" .$expire;
						C("LtCookie")->setCookie('user_auth', $authCode, $expire);
					}
					
					$this->code	= 200;
					$this->data['forward'] = C('LtUrl')->generate('User', 'Index');
				}
				else
				{
					$this->code	= 500;
				}
				
			}
			else
			{
				$this->code	= 500;
			}
		}
		else
		{
			//登陆状态，不允许注册
			$this->code	= 500;
		}
	}
}
